package dk.itu.spvc.bluefriends;

import dk.itu.spvc.bluefriends.classes.Constant;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class ProfileActivity extends BlueFriends{
	public static final String TAG = "ProfileActivity";
	private EditText writeUserNameView;
	private EditText writeEmailView;
	private RadioButton selectRadioMale;
	private RadioButton selectRadioFemale;
	private BluetoothAdapter btAdapter;
	
	//this is to indicate whether the activity should exit
	private boolean exit=false;
	
	private boolean isEditing=false;
	private Cursor profileCs;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profile);
		writeUserNameView = (EditText)findViewById(R.id.editName);
		writeEmailView = (EditText)findViewById(R.id.editEmail);
		selectRadioMale = (RadioButton)findViewById(R.id.radioMale);
		selectRadioFemale = (RadioButton) findViewById(R.id.radioFemale);
		btAdapter=BluetoothAdapter.getDefaultAdapter();
		String[] proj2 = new String[]{
        		BaseColumns._ID,
        		Constant.USERNAME, 
        		Constant.EMAIL,
        		Constant.GENDER,
        		Constant.IMAGE,
        		Constant.ISPENDING,
        		Constant.TIMESTAMP,
        		Constant.MACADDR,
        		Constant.PHONENB
		};
		/**
		 * if we do this checking in TweetActivity, the beddernet service can not be started.
		 * I dont know why yet. let s just check it here.
		*/
		Intent getInte = getIntent();
		isEditing = getInte.getBooleanExtra("isEditing", false);
		profileCs = getContentResolver().query(Constant.PROFILE_CONTENT_URI, proj2, null, null, null);
		profileCs.moveToFirst();
		if(profileCs.getCount()!=0){
			myProfile.setUserName(profileCs.getString(1));
			myProfile.setEmail(profileCs.getString(2));
			myProfile.setGender(profileCs.getString(3));
			myProfile.setMacAddr(profileCs.getString(7));
			myProfile.setPhoneNm(profileCs.getString(8));
			if(!isEditing){
				if(profileCs.getCount() == 1){
					insertTestDataToDB();
				}
				
				Intent intent=new Intent(this,TabContainer.class);
				startActivity(intent);	
			}
		}
	}
	
	//this is to handle whether users is going back from other activities,
	//we do not want users to see this activity when users press back button.
	@Override
	public void onStart(){
		super.onStart();
		if(exit && !isEditing){
			finish();
		}
		exit=true;
	}
	
	public void saveProfile(View v){
		//ToDo: Set keybord to something like android:windowSoftInputMode
		//ToDo: get PhoneNb from phone
		Log.d(TAG, "Saving profile 1");
		String userName = writeUserNameView.getText().toString();
		String email = writeEmailView.getText().toString();
		String gender = "";
		if (selectRadioMale.isChecked()){
			gender = selectRadioMale.getText().toString();
		}
		else if (selectRadioFemale.isChecked()){
			gender = selectRadioFemale.getText().toString();
		}
		
		myProfile.setUserName(userName);
		myProfile.setEmail(email);
		myProfile.setGender(gender);
		myProfile.setMacAddr(btAdapter.getAddress());
		
		String errors = validateProfile(userName, email, gender);
		if (errors.length() > 0) {
			Alerts.showInfoDialog(this, "Please fix errors", errors);
		} else {
			long timeStamp = System.currentTimeMillis();
			ContentValues cv = new ContentValues();
			cv.put(Constant.USERNAME, userName);
			cv.put(Constant.EMAIL, email);
			cv.put(Constant.GENDER, gender);
			cv.put(Constant.IMAGE, "");
			cv.put(Constant.ISPENDING, " ");
			cv.put(Constant.TIMESTAMP, timeStamp);
			cv.put(Constant.MACADDR, myProfile.getMacAddr());
			cv.put(Constant.PHONENB, "123456");
			
			Uri newUri = null;
			int rowId = 0;
			if(profileCs.getCount() == 0){
				newUri = getContentResolver().insert(Constant.PROFILE_CONTENT_URI,  cv);
			}else{
				rowId = getContentResolver().update(Constant.PROFILE_CONTENT_URI, cv, "1", null);
			}
			if(newUri != null || rowId>0){
				//we use Toast because when users go back to edit profile, they wont see dialog again.
				Toast.makeText(this, "well done, Profile saved!", Toast.LENGTH_SHORT);
				Intent intent=new Intent(this,TabContainer.class);
				startActivity(intent);
			}

			else{
				//ToDo:  Handle if Profile not inserted
				Log.d(TAG, "A mess......Profile not inserted");
			}		
		}

	}

	private static String validateProfile(String userName, String email, 
			String gender) {
		StringBuilder errors = new StringBuilder();
		if (userName.matches("^\\s*$")) {
			errors.append("username required\n");
		}

		if (email.matches("^\\s*$")) {
			errors.append("email required\n");
		}

		if (gender.matches("^\\s*$")) {
			errors.append("Gender required\n");
		}
		return errors.toString();
	}


}
